<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <el-page-header :content="this.$route.query.id?'编辑企业':'增加企业'" @back="$router.back()" />
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="addForm" label-width="100px" :model="addForm" :rules="addFromRules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode" placeholder="请选择">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :value="item.industryCode"
                  :label="item.industryName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <el-upload
                action="#"
                :file-list="fileList"
                :http-request="uploadRequest"
                :before-upload="beforeUpload"
                :limit="1"
                :on-exceed="handleExceed"
                :on-remove="handleRemove"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="createExterprise">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { getEnterpriseDatailAPI, createEnterpriseAPI, getIndustryListAPI, uploadAPI, editEnterpriseAPI } from '@/api/Enterprise'
export default {
  data() {
    return {
      // 所在行业
      industryList: [],
      fileList: [],
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      addFromRules: {
        name: [
          { required: true, message: '企业名称不可为空', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '法人不可为空', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '注册地址不可为空', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '所在行业不可为空', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '企业联系人不可为空', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '联系人电话不可为空', trigger: 'blur' },
          { pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
            message: '请输入正确格式的手机号', trigger: 'blur'
          }
        ],
        businessLicenseUrl: [
          { required: true, message: '营业执照url不可为空', trigger: 'blur' }
        ],
        businessLicenseId: [
          { required: true, message: '营业执照ID不可为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getIndustryList()
    if (this.$route.query.id) {
      this.getEnterpriseDatail()
    }
  },
  methods: {
    async getIndustryList() {
      const res = await getIndustryListAPI()
      this.industryList = res.data
    },
    async uploadRequest(data) {
      const file = data.file
      // 处理formData类型参数
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 'businessLicense')
      console.log(formData)

      const res = await uploadAPI(formData)
      // console.log(res)

      // 赋值表单数据
      this.addForm.businessLicenseId = res.data.id
      this.addForm.businessLicenseUrl = res.data.url
      // 自动校验没有更新，上传完成之后，手动在校验一次，更新校验结果
      this.$refs.addForm.validate((valid) => {
        console.log(valid)
      })
    },
    // 编写校验逻辑
    beforeUpload(file) {
      // console.log('上传前', file)
      const allowImgType = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!allowImgType) {
        this.$message.error('上传合同图片只能是 PNG/JPG/JPEG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传合同图片大小不能超过 5MB!')
      }
      return allowImgType && isLt5M
    },
    // 新增企业
    createExterprise() {
      // 表单统一校验
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          if (this.$route.query.id) {
            // console.log('Route ID:', this.$route.query.id)
            await editEnterpriseAPI({
              ...this.addForm,
              id: this.$route.query.id
            })
            this.$message.success('更新成功')
          } else {
            const res = await createEnterpriseAPI(this.addForm)
            // console.log(res)
            if (res.code === 10000) {
              this.$message.success('新增成功')
            } else {
              this.$message.error('新增失败' + res.msg)
            }
          }
          this.$router.back()
        }
      })
    },
    // 清空表单
    resetForm() {
      this.$refs.addForm.resetFields()
    },
    // 获取表单详情
    async getEnterpriseDatail() {
      const { data } = await getEnterpriseDatailAPI(this.$route.query.id)
      console.log(data)
      this.businessLicenseId = data.businessLicenseId
      this.addForm = {
        name: data.name, // 企业名称
        legalPerson: data.legalPerson, // 法人
        registeredAddress: data.registeredAddress, // 注册地址
        industryCode: data.industryCode, // 所在行业
        contact: data.contact, // 企业联系人
        contactNumber: data.contactNumber, // 联系人电话
        businessLicenseUrl: data.businessLicenseUrl, // 营业执照url
        businessLicenseId: data.businessLicenseId // 营业执照id
      }
      this.fileList = [{
        name: data.businessLicenseId,
        url: data.businessLicenseUrl
      }]
    },
    handleExceed(file, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${file.length} 个文件，共选择了 ${file.length + fileList.length} 个文件`)
    },
    handleRemove(file, fileList) {
      this.addForm.businessLicenseId = ''
      this.addForm.businessLicenseUrl = ''
    }
  }

}
</script>

  <style scoped lang="scss">
  .add-enterprise {
    background-color: #f4f6f8;
    height: 100vh;

    .add-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
      height: 64px;
      line-height: 64px;
      font-size: 16px;
      font-weight: bold;
      background-color: #fff;

      .left {
        span {
          margin-right: 4px;
        }
        .arrow{
          cursor: pointer;
        }
      }

      .right {
        text-align: right;
      }
    }

    .add-main {
      background: #f4f6f8;
      padding: 20px 130px;

      .form-container {
        background-color: #fff;
        .title {
          height: 60px;
          line-height: 60px;
          padding-left:20px;
        }
        .form {
          margin-bottom: 20px;
          padding: 20px 65px 24px;
          .el-form{
            display: flex;
            flex-wrap: wrap;
            .el-form-item{
              width: 50%;
            }
          }
        }
      }
    }

    .add-footer {
      position: fixed;
      bottom: 0;
      width: 100%;
      padding: 24px 50px;
      color: #000000d9;
      font-size: 14px;
      background: #fff;
      text-align: center;
    }
  }
  </style>
